package com.gitee.magic.context.converter.list;

import java.util.ArrayList;
import java.util.List;

import com.gitee.magic.context.ConverterEditorUtils;
import com.gitee.magic.context.PropertyConverterEditor;
import com.gitee.magic.core.converter.AbstractConverterEditor;
import com.gitee.magic.core.json.JsonArray;

/**
 * @author start
 */
public class BaseListConverterEditor extends AbstractConverterEditor<String> {
	
	private AbstractConverterEditor<?> editor;

	public BaseListConverterEditor(Class<?> prototype) {
		super(prototype);
		editor=PropertyConverterEditor.getBasicConverter(prototype);
	}

	@Override
	public void restore(Object value) {
		if (value != null) {
			Class<?> target=value.getClass();
			JsonArray json;
			if(target.equals(JsonArray.class)) {
				json=(JsonArray)value;
			}else {
				json=new JsonArray(String.valueOf(value));
			}
			List<Object> list=new ArrayList<>();
			for(int i=0;i<json.length();i++) {
				editor.restore(json.get(i));
				list.add(editor.getValue());
			}
			setValue(list);
		}
	}
	
	@Override
	public String converter() {
		if (getSource() == null) {
			return null;
		}
		return getSource().toString();
	}

	@Override
	public void setValue(Object v) {
		super.setValue(v);
		if(getValue()!=null) {
			JsonArray json=new JsonArray();
			List<?> list=(List<?>)getValue();
			for(Object o:list) {
				AbstractConverterEditor<?> gEditor=ConverterEditorUtils.getBasicConverter(o.getClass());
				gEditor.setValue(o);
				json.put(gEditor.getSource());
			}
			setSource(json);
		}
	}

}
